/**
 * 知识卡片相关工具函数
 */

import type { KnowledgeDetail, KeyPoint } from '@/types';

/**
 * 解析知识卡片数据，确保keyPointsFinal字段正确
 * 
 * @param {any} card - 知识卡片数据
 * @returns {KnowledgeDetail} 解析后的知识卡片
 */
export function parseKnowledgeCard(card: any): KnowledgeDetail {
	let keyPointsFinal: KeyPoint[] = [];
	
	// 优先使用keyPointsFinal字段
	if (card.keyPointsFinal) {
		if (Array.isArray(card.keyPointsFinal)) {
			// 验证每个元素是否包含必要的point和code属性
			keyPointsFinal = card.keyPointsFinal
				.filter((item: any) => item && typeof item === 'object' && 'point' in item && 'code' in item)
				.map((item: { point: any; code: any; }) => ({
					point: String(item.point || ''),
					code: String(item.code || '')
				}));
		} else if (typeof card.keyPointsFinal === 'string') {
			try {
				const parsed = JSON.parse(card.keyPointsFinal);
				if (Array.isArray(parsed)) {
					// 验证每个元素是否包含必要的point和code属性
					keyPointsFinal = parsed
						.filter(item => item && typeof item === 'object' && 'point' in item && 'code' in item)
						.map(item => ({
							point: String(item.point || ''),
							code: String(item.code || '')
						}));
				}
			} catch (e) {
				console.warn('[Knowledge] 解析 keyPointsFinal 失败:', card.keyPointsFinal, e);
			}
		}
	}
	
	return {
		...card,
		keyPointsFinal
	};
}

